<template>
    <view class="pb-safe-area">
        <view class="x-navbar x-navbar-sticky x-navbar-body" :style="[`--bg-opacity:${opacity.navbar}`, '--padding:0px', `padding-top:${PLATFORM.statusBarHeight}px`]">
            <view class="x-navbar-icons" @tap="$page.back()">
                <uni-icons type="left" size="24" color="var(--xl-primary-dark-3)"></uni-icons>
            </view>
            <view class="x-navbar-icons"></view>
            <view class="x-navbar-content" style="opacity: var(--bg-opacity);">
                <text class="text-primary h6 font-weight-700 text-ellipsis-1 x-navbar-title">服务详情</text>
            </view>
            <view class="x-navbar-icons"></view>
            <view class="x-navbar-icons"></view>
        </view>
        <view class="p-4 flex flex-column grid-gap-6" v-if="info.id">
            <view class="flex flex-column bg-white rounded-4 p-4">
                <view class="flex flex-column flex-center grid-gap-2" v-if="info.verification">
                    <uni-icons type="checkbox-filled" size="64" color="var(--xl-primary)"></uni-icons>
                    <text class="font-weight-600 text-primary">核验成功</text>
                    <text class="h9 text-primary">{{ info.verification_time }}</text>
                </view>
                <view class="flex flex-column flex-center grid-gap-2" v-else>
                    <uni-icons type="clear" size="64" color="var(--xl-danger)"></uni-icons>
                    <text class="font-weight-600 text-danger">项目还未核验</text>
                </view>
                <view class="flex flex-column grid-gap-4 p-6">
                    <view class="flex">
                        <text class="w-100px h10 text-placeholder">预约时间</text>
                        <text class="flex-1 h10">{{ info.start_time }}</text>
                    </view>
                    <view class="flex">
                        <text class="w-100px h10 text-placeholder">服务时长</text>
                        <text class="flex-1 h10">{{ info.duration }}分钟</text>
                    </view>
                    <view class="flex">
                        <text class="w-100px h10 text-placeholder">计划通勤时长</text>
                        <text class="flex-1 h10">{{ info.commuting_duration }}分钟</text>
                    </view>
                    <view class="flex">
                        <text class="w-100px h10 text-placeholder">计划抵达时间</text>
                        <text class="flex-1 h10">{{ info.plan_arrival_time }}</text>
                    </view>
                    <view class="flex" v-if="info.commuting_time">
                        <text class="w-100px h10 text-placeholder">实际通勤时长</text>
                        <text class="flex-1 h10" :class="{ 'text-danger': info.timeout, 'text-primary': !info.timeout }">{{
                            $func.getTimeText(info.commuting_time) }}</text>
                    </view>
                    <view class="flex">
                        <text class="w-100px h10 text-placeholder">实际抵达时间</text>
                        <text class="flex-1 h10">{{ info.arrival_time }}</text>
                    </view>
                    <view class="flex flex-y-center" v-if="info.time > 0 && info.state === 4">
                        <text class="w-100px h10 text-placeholder">剩余服务时长</text>
                        <x-countdown class="h1 text-primary" :time="info.time" @end="getDetails" />
                    </view>
                    <view class="flex flex-y-center" v-if="info.state === 2 && [2, 3].includes(info.orders_state) && WEBCONFIG?.arrival_photo">
                        <text class="w-100px h10 text-placeholder">到达照片</text>
                        <view class="flex-1 flex flex-column grid-gap-2">
                            <x-uploads v-model="arrivalPhoto" :limit="1" type="image" :col="1" :margins="212" :gap="0" />
                            <text class="h10 text-placeholder" v-if="WEBCONFIG.arrival_photo_tips">{{
                                WEBCONFIG.arrival_photo_tips }}</text>
                        </view>
                    </view>
                    <view class="flex flex-y-center" v-else-if="info.state === 3 && info.verification && [2, 3].includes(info.orders_state) && WEBCONFIG?.service_start_photo">
                        <text class="w-100px h10 text-placeholder">开始服务拍照</text>
                        <view class="flex-1 flex flex-column grid-gap-2">
                            <x-uploads v-model="serviceStartPhoto" :limit="1" type="image" :col="1" :margins="212" :gap="0" />
                            <text class="h10 text-placeholder" v-if="WEBCONFIG.service_start_photo_tips">{{
                                WEBCONFIG.service_start_photo_tips }}</text>
                        </view>
                    </view>
                    <view class="flex flex-y-center" v-else-if="info.state === 4 && [2, 3].includes(info.orders_state) && WEBCONFIG?.service_end_photo">
                        <text class="w-100px h10 text-placeholder">结束服务照片</text>
                        <view class="flex-1 flex flex-column grid-gap-2">
                            <x-uploads v-model="serviceEndPhoto" :limit="1" type="image" :col="1" :margins="212" :gap="0" />
                            <text class="h10 text-placeholder" v-if="WEBCONFIG.service_end_photo_tips">{{
                                WEBCONFIG.service_end_photo_tips }}</text>
                        </view>
                    </view>
                </view>
                <view class="flex grid-gap-4 flex-y-center info-action">
                    <button class="btn-warning btn-round" v-if="[2, 3].includes(info.orders_state)" @tap.stop="$page.open('/technician/pages/order/refund?trade=' + info.trade, true)">
                        申请退单
                    </button>
                    <button class="flex-1 btn-info-light-3 btn-round" v-else-if="info.orders_state === 90">
                        退单中
                    </button>
                    <button class="flex-1 btn-primary btn-round" v-if="info.state === 1 && [2, 3].includes(info.orders_state)" @tap="departureModal">出发</button>
                    <button class="flex-1 btn-danger-light-2 btn-round" v-else-if="info.state === 2 && [2, 3].includes(info.orders_state)" @tap="arrivalModal">抵达</button>
                    <!-- #ifdef H5 -->
                    <button class="flex-1 btn-dark-light-3 btn-round text-nowarp" v-else-if="info.state === 3 && !info.verification && [2, 3].includes(info.orders_state)" disabled>请使用微信扫描核验码</button>
                    <!-- #endif -->
                    <!-- #ifndef H5 -->
                    <button class="flex-1 flex flex-center grid-gap-2 btn-primary btn-round" v-else-if="info.state === 3 && !info.verification && [2, 3].includes(info.orders_state)" @tap="$func.scanCode()">
                        <uni-icons type="scan" color="#FFFFFF" size="20"></uni-icons>
                        <text>扫码核验</text>
                    </button>
                    <!-- #endif -->
                    <button class="flex-1 btn-primary btn-round" v-else-if="info.state === 3 && info.verification && [2, 3].includes(info.orders_state)" @tap="startServiceModal">开始服务</button>
                    <button class="flex-1 btn-danger-light-2 btn-round text-nowarp" v-else-if="info.state === 4 && [2, 3].includes(info.orders_state)" @tap="endServiceModal">
                        <text>结束服务</text>
                    </button>
                </view>
            </view>

            <!-- 预约项目 -->
            <view class="p-4 rounded-4 bg-white flex flex-column grid-gap-4">
                <view class="flex flex-y-center grid-gap-2">
                    <text class="bg-primary-light-3 rounded-4" style="height: 8px;width: 8px;"></text>
                    <text class="h9 font-weight-600">预约项目</text>
                </view>
                <view class="flex flex-column grid-gap-4 bg">
                    <view class="bg-white py-2">
                        <x-project-item :project="info">
                            <template #action>
                                <view @tap.stop class="flex flex-center grid-gap-1">
                                    <text class="text-placeholder">x</text>
                                    <text class="font-weight-600 text-grey" v-if="info.num > 0">{{ info.num }}</text>
                                </view>
                            </template>
                        </x-project-item>
                    </view>
                </view>
            </view>

            <!-- 加钟详情 -->
            <view class="p-4 rounded-4 bg-white flex flex-column grid-gap-4" v-if="info.sub_orders && info.sub_orders.length">
                <view class="flex flex-y-center grid-gap-2">
                    <text class="bg-primary-light-3 rounded-4" style="height: 8px;width: 8px;"></text>
                    <text class="h9 font-weight-600">加钟记录</text>
                </view>

                <view class="flex flex-column grid-gap-3">
                    <view v-for="(item, index) in info.sub_orders" :key="index" class="overtime-item flex flex-column p-4 rounded-4" :class="{ 'overtime-unpaid': item.state === 0 }">
                        <view class="mb-3">
                            <text class="h10 text-placeholder">订单号：</text>
                            <text class="h10">{{ item.trade }}</text>
                        </view>

                        <view class="flex flex-x-space-between mb-3">
                            <text class="font-weight-600 h8">{{ item.title }}</text>
                            <text class="text-primary font-weight-600 h7">¥{{ item.price }}</text>
                        </view>

                        <view class="flex flex-x-space-between mb-2">
                            <view class="flex grid-gap-2 flex-y-center">
                                <text class="text-placeholder h10">时长</text>
                                <text class="h9">{{ item.service_duration }}分钟</text>
                            </view>
                            <view class="flex grid-gap-2 flex-y-center">
                                <text class="text-placeholder h10">状态</text>
                                <view class="status-tag" :class="{
                                    'status-unpaid': item.state === 0,
                                    'status-completed': item.state === 4
                                }">
                                    {{ item.state === 0 ? '未支付' : '已支付' }}
                                </view>
                            </view>
                        </view>

                        <view class="border-top pt-2">
                            <text class="text-placeholder h10">{{ item.create_time }}</text>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 订单详情 -->
            <view class="p-4 rounded-4 bg-white flex flex-column grid-gap-4">
                <view class="flex flex-y-center grid-gap-2">
                    <text class="bg-primary-light-3 rounded-4" style="height: 8px;width: 8px;"></text>
                    <text class="h9 font-weight-600">订单信息</text>
                </view>
                <view class="flex flex-column grid-gap-4" v-if="info.to_shop">
                    <view class="flex flex-y-center flex-x-space-between">
                        <text class="h9 text-grey">客户</text>
                        <view class="flex flex-center grid-gap-1">
                            <image :src="info.headimg" mode="scaleToFill" class="rounded-circle" style="width: 20px;height: 20px;" />
                            <text class="h10 text-primary font-weight-600">{{ info.nickname }}</text>
                        </view>
                    </view>
                    <view class="flex flex-y-center flex-x-space-between">
                        <text class="text-grey h9">电话</text>
                        <text class="h10 text-primary font-weight-600" hover-class="bg" selectable user-select @tap="$api.AppointmentService.makePhoneCall({ id: info.id, action: 'technician' })">{{
                            info.mobile
                        }}</text>
                    </view>
                </view>
                <view class="flex flex-column grid-gap-4" v-else>
                    <view class="flex flex-y-center flex-x-space-between">
                        <text class="h9 text-grey">客户</text>
                        <view class="flex flex-center grid-gap-1">
                            <image :src="info.headimg" mode="scaleToFill" class="rounded-circle" style="width: 20px;height: 20px;" />
                            <text class="h10 text-primary font-weight-600">{{ info.name }}</text>
                        </view>
                    </view>
                    <view class="flex flex-y-center flex-x-space-between">
                        <text class="text-grey h9">电话</text>
                        <text class="h10 text-primary font-weight-600" hover-class="bg" selectable user-select @tap="$api.AppointmentService.makePhoneCall({ id: info.id, action: 'technician' })">{{
                            info.mobile
                        }}</text>
                    </view>
                    <view class="flex flex-y-center flex-x-space-between grid-gap-2" @tap="openLocation">
                        <text class="text-grey h9 text-nowrap">地址</text>
                        <text class="flex-1 h10 text-primary font-weight-600" hover-class="bg" selectable user-select @tap="$func.setClipboard(`${info.province}${info.city}${info.area}${info.street}${info.address_detail}`)">
                            {{ info.province }}{{ info.city }}{{ info.area }}{{ info.street }}{{ info.address_detail }}
                        </text>
                        <image src="/static/icons/map-icon.png" mode="aspectFit" class="x-navbar-icons-image" style="width: 20px; height: 20px;" v-if="info.longitude && info.latitude" />
                    </view>
                </view>
                <view class="flex flex-y-center flex-x-space-between">
                    <text class="text-grey h9">订单编号</text>
                    <text class="h10 text-dark font-weight-600" hover-class="bg" selectable user-select>{{ info.trade
						}}</text>
                </view>
                <view class="flex flex-y-center flex-x-space-between">
                    <text class="text-grey h9">预约时间</text>
                    <text class="h10 text-dark font-weight-600" hover-class="bg" selectable user-select>{{
                        info.start_time }}</text>
                </view>
                <view class="flex flex-y-center flex-x-space-between">
                    <text class="text-grey h9">订单备注</text>
                    <text class="h10 text-dark font-weight-600">{{ info.remark }}</text>
                </view>
            </view>

        </view>
        <x-loading v-if="loading" />
        <x-one-click-alarm role="technician" />
    </view>
</template>

<script setup lang="ts">
import { ref, watch, onBeforeUnmount } from "vue";
import { onLoad, onShow, onPageScroll, onUnload } from "@dcloudio/uni-app";
import { $api, $func, $message, $page } from "@/utils";
import { useMap } from "@/utils/map";
import { usePlatformStore, useWebConfigStore, useRefs } from "@/stores";
import { $EventName } from "@/utils/const/env";
const PlatformStore = usePlatformStore();
const { PLATFORM } = useRefs(PlatformStore);
const WebConfigStore = useWebConfigStore();
const { WEBCONFIG } = useRefs(WebConfigStore);
let map: any;
const opacity = ref<{
    navbar: number | string
}>({
    navbar: 0,
});
const top = ref(0);
watch(() => top.value, (val: number) => {
    if (val < -10) {
        return;
    }
    opacity.value.navbar = val > 50 ? 1 : (val / 50).toFixed(1);
})
onPageScroll(({ scrollTop }: { scrollTop: number }) => {
    top.value = scrollTop;
})
const arrivalPhoto = ref('');
const serviceStartPhoto = ref('');
const serviceEndPhoto = ref('');
const loading = ref(false);
const search = ref({
    id: '',
    action: 'technician'
});
const info = ref({});
const getDetails = () => {
    loading.value = true
    $api.AppointmentService.details(search.value).then((data: any) => {
        info.value = data
        if (data.arrival_time) {
            const arrival_time = new Date(data.arrival_time.replace(/-/g, '/'));
            const plan_arrival_time = new Date(data.start_time.replace(/-/g, '/'));
            plan_arrival_time.setMinutes(plan_arrival_time.getMinutes() + data.commuting_duration);
            info.value.plan_arrival_time = `${$func.getDayName(plan_arrival_time)} ${plan_arrival_time.getHours().toString().padStart(2, '0')}:${plan_arrival_time.getMinutes().toString().padStart(2, '0')}`;
            info.value.timeout = false;
            if (arrival_time > plan_arrival_time) {
                info.value.timeout = true;
            }
        }
        if (data.state === 4) {
            const service_start_time = new Date(data.service_start_time.replace(/-/g, '/'));
            service_start_time.setMinutes(service_start_time.getMinutes() + data.duration);
            const now = new Date;
            info.value.time = (service_start_time.getTime() - now.getTime()) / 1000;
        }
    }).catch(() => {
    }).finally(() => {
        loading.value = false
    })
}
const departure = (data: any) => {
    $api.AppointmentService.departure(data).then(() => {
        getDetails()
    }).catch((err: any) => {
        loading.value = false
        $message.error(err.msg);
    })
}
const departureModal = () => {
    uni.showModal({
        title: '提示',
        content: '请确认您已整装待发。',
        confirmText: '确认出发',
        success: (res) => {
            if (res.confirm) {
                loading.value = true
                map.getCurrentPosition({
                    altitude: false,
                    geocode: false
                }).then((result: any) => {
                    departure({
                        id: info.value.id,
                        latitude: result.position.lat,
                        longitude: result.position.lng
                    })
                }).catch(() => {
                    departure({
                        id: info.value.id
                    })
                });
            }
        }
    })
}
const arrival = (data: any) => {
    data.arrival_photo = arrivalPhoto.value;
    $api.AppointmentService.arrival(data).then(() => {
        getDetails()
    }).catch((err: any) => {
        loading.value = false
        $message.error(err.msg);
    })
}
const arrivalModal = () => {
    if (!arrivalPhoto.value && WEBCONFIG.value?.arrival_photo) {
        $message.error('请上传到达照片');
        return;
    }
    uni.showModal({
        title: '提示',
        content: '请确认您到达指定地点。',
        confirmText: '确认到达',
        success: (res) => {
            if (res.confirm) {
                loading.value = true;
                map.getCurrentPosition({
                    altitude: false,
                    geocode: false
                }).then((result: any) => {
                    arrival({
                        id: info.value.id,
                        latitude: result.position.lat,
                        longitude: result.position.lng
                    })
                }).catch(() => {
                    arrival({
                        id: info.value.id
                    })
                });
            }
        }
    })
}
const startService = (data: any) => {
    data.service_start_photo = serviceStartPhoto.value;
    $api.AppointmentService.startService(data).then(() => {
        getDetails()
    }).catch((err: any) => {
        loading.value = false
        $message.error(err.msg);
    })
}
const startServiceModal = () => {
    if (!serviceStartPhoto.value && WEBCONFIG.value?.service_start_photo) {
        $message.error('请上传开始服务照片');
        return;
    }
    uni.showModal({
        title: '提示',
        content: '请确认您已准备好开始服务。',
        confirmText: '确认开始',
        success: (res) => {
            if (res.confirm) {
                loading.value = true;
                map.getCurrentPosition({
                    altitude: false,
                    geocode: false
                }).then((result: any) => {
                    console.log(result);
                    startService({
                        id: info.value.id,
                        latitude: result.position.lat,
                        longitude: result.position.lng
                    })
                }).catch(() => {
                    startService({
                        id: info.value.id
                    })
                });
            }
        }
    })
}
const endService = (data: any) => {
    data.service_end_photo = serviceEndPhoto.value;
    $api.AppointmentService.endService(data).then(() => {
        getDetails()
    }).catch((err: any) => {
        loading.value = false;
        $message.error(err.msg);
    })
}
const endServiceModal = () => {
    if (!serviceEndPhoto.value && WEBCONFIG.value?.service_end_photo) {
        $message.error('请上传结束服务照片');
        return;
    }
    if (info.value.state === 4) {
        const service_start_time = new Date(info.value.service_start_time.replace(/-/g, '/'));
        service_start_time.setMinutes(service_start_time.getMinutes() + info.value.duration);
        const now = new Date;
        info.value.time = (service_start_time.getTime() - now.getTime()) / 1000;
        if (info.value.time > 0) {
            uni.showModal({
                title: '提示',
                content: '当前服务时间还未结束，是否确认提前结束服务？如有加钟需要退款，请先引导用户申请退款在结束服务。',
                success: (res) => {
                    if (res.confirm) {
                        loading.value = true;
                        map.getCurrentPosition({
                            altitude: false,
                            geocode: false
                        }).then((result: any) => {
                            endService({
                                id: info.value.id,
                                action: search.value.action,
                                latitude: result.position.lat,
                                longitude: result.position.lng
                            })
                        }).catch(() => {
                            endService(search.value)
                        });

                    }
                }
            })
        } else {
            map.getCurrentPosition({
                altitude: false,
                geocode: false
            }).then((result: any) => {
                endService({
                    id: info.value.id,
                    action: search.value.action,
                    latitude: result.position.lat,
                    longitude: result.position.lng
                })
            }).catch(() => {
                endService(search.value)
            });
        }
    }
}
const useInitMap = () => {
    map = useMap();
}
const openLocation = () => {
    if (!info.value.longitude || !info.value.latitude) {
        return;
    }
    uni.openLocation({
        latitude: info.value.latitude,
        longitude: info.value.longitude,
        name: info.value.address_detail,
        address: `${info.value.province}${info.value.city}${info.value.area}${info.value.street}${info.value.address_detail}`
    });
}
onLoad((options: any) => {
    search.value.id = options.id
    getDetails();
    useInitMap();
    uni.$once($EventName.WEBCONFIG_READY, useInitMap)
})
onShow(() => {
    getDetails();
})
onBeforeUnmount(() => {
    uni.$off($EventName.WEBCONFIG_READY, useInitMap);
});

</script>
<style lang="scss">

    /* #ifdef H5 */
    uni-page[data-page="technician/pages/user/service/details"] {

        /* #endif */
        page {
            background: radial-gradient(circle at 15% 20%, var(--xl-primary) -100%, transparent 35%),
                radial-gradient(circle at 27% 5%, var(--xl-primary-light-3) -50%, transparent 30%),
                radial-gradient(circle at 85% 17%, var(--xl-primary-light-1) -50%, transparent 25%);
            background-repeat: no-repeat;
            background-position: top center;
            background-color: $uni-bg-color-grey;
            /* #ifdef H5 */
            background-attachment: fixed;
            /* #endif */
        }

        /* #ifdef H5 */
    }

    /* #endif */
</style>
<style lang="scss" scoped>
    .w-100px {
        width: 100px;
    }

    @media (max-width: 350px) {
        .info-action {
            flex-direction: column-reverse;
        }
    }

    .border-bottom {
        border-bottom: 1px solid var(--xl-gray-100);
    }


    .bg-gray-50 {
        background-color: #f9fafb;
    }

    .text-gray {
        color: #6b7280;
    }

    .mb-2 {
        margin-bottom: 8px;
    }

    .mb-3 {
        margin-bottom: 12px;
    }

    .overtime-item {
        background: #FFFFFF;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
        transition: all 0.3s ease;

        &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        }
    }

    .overtime-unpaid {
        background: #FFF8F8;
        border: 1px solid rgba(var(--xl-danger-rgb), 0.1);
    }

    .status-tag {
        padding: 2px 8px;
        border-radius: 12px;
        font-size: 12px;
    }

    .status-unpaid {
        background: rgba(var(--xl-danger-rgb), 0.1);
        color: var(--xl-danger);
    }

    .status-completed {
        background: rgba(var(--xl-success-rgb), 0.1);
        color: var(--xl-success);
    }

    .border-top {
        border-top: 1px solid rgba(0, 0, 0, 0.05);
    }

    .pt-2 {
        padding-top: 8px;
    }
</style>
